
#include "bullet_System.h"
#include "bullet_Ground.h"
#include "bullet_Rigid.h"
#include "bullet_Joint.h"

#include "bullet_DebugDraw.h"

using std::vector;

BulletSystem::~BulletSystem() = default;

BulletSystem::BulletSystem() :
m_upCollisionConfigtation(new btDefaultCollisionConfiguration()),
m_upDispatcher(new btCollisionDispatcher(m_upCollisionConfigtation.get())),
m_upPairCache(new btDbvtBroadphase()),
m_upSolver(new btSequentialImpulseConstraintSolver),
m_upWorld(new btDiscreteDynamicsWorld(m_upDispatcher.get(), m_upPairCache.get(), m_upSolver.get(), m_upCollisionConfigtation.get())),
m_upGround(new BulletGround(m_upWorld))
{
	m_upWorld->setGravity(btVector3(0.0f, -49.0f, -0.0f));
	m_upGround->AttachToWorld();
}

void BulletSystem::StepSimulation()
{
	m_upWorld->stepSimulation(1.0f/60.0f, 10);
}

IPhysicsRigid* BulletSystem::CreateRigid(RigidBodyParam &param)
{
	return new BulletRigid(m_upWorld, param);
}

IPhysicsJoint* BulletSystem::CreateJoint(JointParam &param, IPhysicsRigid &rigid_1, IPhysicsRigid &rigid_2)
{
	return new BulletJoint(m_upWorld, param, rigid_1, rigid_2);
}

void BulletSystem::CreateDebugDraw(vector<PhysicsDebugVertex> &rVertex)
{
	m_upDebug.reset(new BulletDebugDraw(rVertex));
	m_upWorld->setDebugDrawer(m_upDebug.get());
	m_upWorld->getDebugDrawer()->setDebugMode(
		btIDebugDraw::DBG_DrawWireframe |
		btIDebugDraw::DBG_DrawConstraints |
		btIDebugDraw::DBG_DrawConstraintLimits);
}

void BulletSystem::DrawDebug()
{
	if(m_upDebug) {
		m_upDebug->ResetVertex();
	}
	m_upWorld->debugDrawWorld();
}

